package library.commands;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import library.domain.User;

public class CommandManager {

    private static CommandManager instance = new CommandManager();

    private CommandManager() {
    }

    public static CommandManager getInstance() {
        return instance;
    }
    public static final Map<String, Class<? extends Command>> commands =
            new HashMap<String, Class<? extends Command>>();

    static {
        commands.put("UPLOAD", UploadCommand.class);
        commands.put("DOWNLOAD", DownloadCommand.class);
        commands.put("SEARCH", SearchCommand.class);
        commands.put("AUTH", AuthCommand.class);

    }
    private Map<Socket, User> sessions = new HashMap<Socket, User>();

    public User getUserForSocket(Socket sock) {
        return sessions.get(sock);
    }

    public void addSession(Socket sock, User user) {
        sessions.put(sock, user);
    }

    public void removeSession(Socket sock) {
        sessions.remove(sock);
    }

    public void execute(String command, Socket socket, ObjectInputStream input, ObjectOutputStream output) throws Exception {
        Command cmd = createCommand(command, socket, input, output);
        if (cmd == null) {
            return;
        }
        cmd.execute();
    }

    private Command createCommand(String command, Socket socket, ObjectInputStream input, ObjectOutputStream output) {
        Class<? extends Command> commandClass = commands.get(command.toUpperCase());
        try {
            return (Command) commandClass.getConstructor(ObjectInputStream.class, ObjectOutputStream.class, Socket.class).newInstance(input, output, socket);
        } catch (Exception e) {
            return null;
        }
    }
}